package com.warmlight.voicepacket;

import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.design.widget.BottomSheetBehavior;
import android.support.v7.app.AlertDialog;
import android.text.TextUtils;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.request.RequestOptions;
import com.google.gson.Gson;
import com.umeng.analytics.MobclickAgent;
import com.warmlight.voicepacket.adapter.PlayDetailMineAdapter;
import com.warmlight.voicepacket.base.BaseActivity;
import com.warmlight.voicepacket.data.PlaydeatalData;
import com.warmlight.voicepacket.data.RecommendFeed;
import com.warmlight.voicepacket.data.eventbus.AudioCompleted;
import com.warmlight.voicepacket.data.eventbus.NotifyMyPlaylist;
import com.warmlight.voicepacket.data.eventbus.NotifyPlayDetal;
import com.warmlight.voicepacket.data.eventbus.PlayerServiceData;
import com.warmlight.voicepacket.dbdata.DBFloatPlayListDetail;
import com.warmlight.voicepacket.dbdata.DBFloatPlaylist;
import com.warmlight.voicepacket.dbmanager.DBFloatPlayListDaoHelp;
import com.warmlight.voicepacket.dbmanager.DBFloatPlayListDetailDaoHelp;
import com.warmlight.voicepacket.fragment.CopyShareFragment;
import com.warmlight.voicepacket.http.HttpClient;
import com.warmlight.voicepacket.http.HttpConfig;
import com.warmlight.voicepacket.ui.user.LoginRegistActivity;
import com.warmlight.voicepacket.utils.ClickLog;
import com.warmlight.voicepacket.utils.GlideCornerTransform;
import com.warmlight.voicepacket.utils.MobClickHelper;
import com.warmlight.voicepacket.utils.SPUtils;
import com.warmlight.voicepacket.utils.ShareCollectCallBackUtils;
import com.warmlight.voicepacket.widget.dslv.DragSortListView;
import com.zhuge.analysis.stat.ZhugeSDK;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.io.IOException;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.TreeMap;

import io.reactivex.Observable;
import io.reactivex.ObservableEmitter;
import io.reactivex.ObservableOnSubscribe;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;
import okhttp3.Call;

import static com.warmlight.voicepacket.db.VoicePacketDBHelper.AUDIO_ID;
import static com.warmlight.voicepacket.db.VoicePacketDBHelper.LIST_ID;
import static com.warmlight.voicepacket.fragment.PlaylistFragment.LOCAL;

/**
 * 我的播单，本地播单
 */
public class PlayDetailMineActivity extends BaseActivity implements View.OnClickListener{


    private DragSortListView footerListView;
    private View vHead;
    private LinearLayout ll_header;
    private PlayDetailMineAdapter adapter=null;
    private LinearLayout ll_play_all, ll_share ,ll_back;
    private TextView tv_desc,tv_header_title,tv_header_titlename;
    private ImageView iv_playimg;
    private  boolean ISBODAN=true;//播单页面
    private  PlaydeatalData.DataBean.ShareBean sharedata;
    private  List<PlaydeatalData.DataBean.ListBean> listBean;
    private  List<PlaydeatalData.DataBean.ListBean> datas=new ArrayList<>();
    public static final int UPDATE = 0x1;
    private int page=1;
    PlaydeatalData playdeatalData;
    private DBFloatPlaylist mPlaylistData;
    private List<DBFloatPlayListDetail> mAudios;
    private ImageView iv_cover_mine;
    private boolean isManager;
    private TextView tv_cancel;
    private TextView tv_select_all;
    private ImageView iv_back;
    private LinearLayout ll_manager;
    private RelativeLayout rl_cover_add;
    private RelativeLayout rl_cover_delete;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_playdeatal_mine);

        if (getIntent().getStringExtra(LIST_ID)!=null){
            ISBODAN=false;
            initView();
            initData();
        }else {
            ISBODAN=true;
            initView();
            Intent intent = getIntent();
            mPlaylistData = (DBFloatPlaylist) intent.getSerializableExtra(LOCAL);
            if ("我的最爱".equals(mPlaylistData.getList_name())){
                iv_cover_mine.setVisibility(View.VISIBLE);
            }else{
                iv_cover_mine.setVisibility(View.GONE);
            }
            tv_header_title.setText(mPlaylistData.getList_name());
//            mAudios = DBHelper.getInstance(getThis()).queryAudiosByListId(mPlaylistData.get_id());
            mAudios = DBFloatPlayListDetailDaoHelp.queryBuilder(getThis(),mPlaylistData.getId()+"");
            datas= changeData(mAudios);
            if(adapter==null){
                adapter = new PlayDetailMineAdapter(getThis(),datas, getSupportFragmentManager(),true);
                footerListView.setAdapter(adapter);
            }
            RequestOptions options = new RequestOptions();
            options.transform(new GlideCornerTransform(this, 8)).dontAnimate();
            if (datas.size()>0){
                if (TextUtils.isEmpty(datas.get(0).getPic())){
                    Glide.with(this).load(R.drawable.icon_iv_fail).apply(options).into(iv_playimg);
                }else {
                    Glide.with(this).load(datas.get(0).getPic()).apply(options).into(iv_playimg);
                }
            }else {
                Glide.with(this).load(R.drawable.icon_iv_fail).apply(options).into(iv_playimg);
            }
            initDataMine();
        }

    }

    private List<PlaydeatalData.DataBean.ListBean> changeData(List<DBFloatPlayListDetail> localData){
        List<PlaydeatalData.DataBean.ListBean> listBeans=new ArrayList<>();
        for (int i=0; i<localData.size();i++){
            PlaydeatalData.DataBean.ListBean bean=new PlaydeatalData.DataBean.ListBean();
            bean.setId(localData.get(i).getAudio_id());
            bean.setCover_id(localData.get(i).getAudio_cover_id());
//            listBeans.get(i).set(localData.get(i).getAudio_ps();
            bean.setTitle(localData.get(i).getAudio_title());
            bean.setUrl(localData.get(i).getAudio_url());
            bean.setPic(localData.get(i).getAudio_ps());
            bean.setCover_name(localData.get(i).getAudio_cover_name());
            listBeans.add(bean);
        }
        return  listBeans;
    }

    private void initData() {
        final TreeMap<String, String> list=new TreeMap<>();
        list.put("cover_id",getIntent().getStringExtra(LIST_ID));
        list.put("page",String.valueOf(page));
        list.put("pagesize","10");

        HttpClient.post(HttpConfig.SERVER+HttpConfig.COVER_DETAIL, list, new com.warmlight.voicepacket.http.Callback() {
            @Override
            public void onFailure(Call call, IOException e) {

            }

            @Override
            public void onResponse(Call call, String response) {
                Gson gson = new Gson();
                playdeatalData = gson.fromJson(response, PlaydeatalData.class);
//                Log.e("onResponse:====1== ",response.body().string());
//                Log.e("onResponse:===3333=== ",playdeatalData.getData().getList().size()+"");
                listBean= playdeatalData.getData().getList();
                for (int j = 0;j<listBean.size();j++){
                    listBean.get(j).setPic(playdeatalData.getData().getCover_info().getPic());
                    datas.add(listBean.get(j));
                }
                sharedata=playdeatalData.getData().getShare();
                Message msg = new Message();
                msg.what = UPDATE;
                mHandler.sendMessage(msg);
            }
        });
    }

    private Handler mHandler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what){
                case UPDATE:

                    PlaydeatalData.DataBean.CoverInfoBean info= playdeatalData.getData().getCover_info();
                    if ("我的最爱".equals(info.getName())){
                        iv_cover_mine.setVisibility(View.VISIBLE);
                    }else{
                        iv_cover_mine.setVisibility(View.GONE);
                    }
                    tv_header_title.setText(info.getName());
                    String uri=info.getPic();
                    RequestOptions options = new RequestOptions();
                    options.transform(new GlideCornerTransform(PlayDetailMineActivity.this,8)).dontAnimate();
                    Glide.with(PlayDetailMineActivity.this).load(TextUtils.isEmpty(uri)?R.drawable.icon_all:uri).apply(options).into(iv_playimg);
//                    listBean.add(listBean.get(0));
//                    Log.e("onResponse:===111=== ",datas.+"");
                    if (adapter==null){
                        adapter = new PlayDetailMineAdapter(PlayDetailMineActivity.this,datas , getSupportFragmentManager(),ISBODAN);
                        footerListView.setAdapter(adapter);
                    }else {
                        adapter.notifyDataSetChanged();
                    }
//                    adapter = new PlayDetalAdapter(PlayDeatalActivity.this,listBean , getSupportFragmentManager(),ISBODAN);
//                    footerListView.setAdapter(adapter);
//                    adapter.addList(listBean);
//                    footerListView.setAdapter(adapter);
//                    if (listBean.size()<20){
//                        footerListView.getFooterView().setVisibility(View.GONE);
//                    }
                    break;
            }

        }
    };

    @Subscribe (threadMode = ThreadMode.MAIN)//(sticky = true)
    public void onEvent(AudioCompleted data){

        if(datas!=null&&adapter!=null){
            for (int j = 0;j<datas.size();j++){
                datas.get(j).setCheak(false);
                datas.get(j).setPause(false);
            }
            adapter.notifyDataSetChanged();
        }
    }

    private void initDataMine(){
        tv_desc.setText("(共"+datas.size()+"首)");
    }

    private void refreshDataSize(){
        tv_desc.setText("(共"+datas.size()+"首)");
    }

    private void initView() {
        EventBus.getDefault().register(this);
        footerListView = (DragSortListView) findViewById(R.id.flv_play);
        vHead = View.inflate(this, R.layout.header_playdetal_mine, null);

        ll_header = (LinearLayout) vHead.findViewById(R.id.ll_header);
//        ll_play_all = (LinearLayout) vHead.findViewById(R.id.ll_play_all);
        ll_share = (LinearLayout) vHead.findViewById(R.id.ll_share);
        ll_share.setOnClickListener(this);
        tv_desc = (TextView) vHead.findViewById(R.id.tv_desc);
        iv_playimg = (ImageView) vHead.findViewById(R.id.iv_playimg);
        iv_cover_mine = (ImageView) vHead.findViewById(R.id.iv_cover_mine);
        tv_header_title = (TextView) vHead.findViewById(R.id.tv_header_title);
        tv_header_titlename= (TextView) findViewById(R.id.tv_header_titlename);
        ll_back= (LinearLayout) findViewById(R.id.ll_back);
        ll_back.setOnClickListener(this);
        tv_select_all = (TextView) findViewById(R.id.tv_select_all);
        tv_select_all.setVisibility(View.GONE);
        tv_cancel = (TextView) findViewById(R.id.tv_cancel);
        iv_back = (ImageView) findViewById(R.id.iv_back);
        tv_select_all.setOnClickListener(this);
        ll_manager = (LinearLayout) findViewById(R.id.ll_manager);
        ll_manager.setVisibility(View.GONE);
        rl_cover_delete = (RelativeLayout) findViewById(R.id.rl_cover_delete);
        rl_cover_add = (RelativeLayout) findViewById(R.id.rl_cover_add);

        if (ISBODAN) {
            tv_header_titlename.setText("我的播单");
//            tv_desc.setVisibility(View.GONE);
//            ll_share.setVisibility(View.GONE);
        } else {
            tv_header_titlename.setText("播单");
        };

        footerListView.addHeaderView(ll_header);

        footerListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                if (i==0||i==datas.size()+1)return;
                if (isManager){
                    selectItem(i-1);
                    return;
                }

                if (!datas.get(i-1).getUrl().contains("http")){
                    if (!SPUtils.isLogined()) {
                        showLoginDialog();
                    }
                    return;
                }

                if (datas.get(i-1).isCheak()){
                    datas.get(i-1).setCheak(false);
                    datas.get(i-1).setPause(true);
                }else{
                    if (!datas.get(i-1).isPause()){
                        ClickLog.clickLog(ClickLog.myclot_feed_play,datas.get(i-1).getCover_id(),
                                datas.get(i-1).getId());
                    }

                    for (int j = 0;j<datas.size();j++){
                        datas.get(j).setCheak(false);
                        datas.get(j).setPause(false);
                    }
                    datas.get(i-1).setCheak(true);
                }

                adapter.notifyDataSetChanged();

                EventBus.getDefault().post(new PlayerServiceData(PlayerServiceData.PLAY,datas.get(i-1).getUrl()));
                //FIXME 我先埋上，重复统计待修复
                if(ISBODAN){
                    //本地播单feed播放单击
                    MobclickAgent.onEvent(getThis().getApplicationContext(), MobClickHelper.MYCLOT_FEED_PLAY,datas.get(i-1).getTitle());
                    HashMap<String,Object> temp = new HashMap<>();
                    temp.put("本地播单feed播放单击",datas.get(i-1).getTitle().toString());
                    ZhugeSDK.getInstance().track(getThis().getApplicationContext(),MobClickHelper.MYCLOT_FEED_PLAY,temp);

                }else{
                    //网络播单
                    MobclickAgent.onEvent(getThis().getApplicationContext(), MobClickHelper.BAG_FEED_PLAY,datas.get(i-1).getTitle());
                    HashMap<String,Object> temp = new HashMap<>();
                    temp.put("网络播单",datas.get(i-1).getTitle().toString());
                    ZhugeSDK.getInstance().track(getThis().getApplicationContext(),MobClickHelper.BAG_FEED_PLAY,temp);

                }
            }
        });

//        if (!ISBODAN){
//
//            footerListView.setOnLastItemVisiableListener(new FooterListView.LastItemVisiableListener() {
//                @Override
//                public void onLastItemVisiable() {
//                    page++;
//                    initData();
//                }
//            });
//        }else {
//            footerListView.getFooterView().setVisibility(View.GONE);
//        }

//        Log.e("onResponse:====2== ",playdeatalData.getData().getList().size()+"");


        initListener();
    }

    private void showLoginDialog() {
        AlertDialog alertDialog = new AlertDialog.Builder(getContext())
                .setTitle("请登录后使用")
                .setMessage("由于功能升级，该语音需登录并上传后才可使用")
                .setPositiveButton("去登录", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        Intent intent = new Intent(getContext(), LoginRegistActivity.class);
                        getContext().startActivity(intent);
                        dialog.dismiss();
                    }
                }).setNegativeButton("取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                    }
                }).create();
        alertDialog.show();
    }
    private void initListener(){
        footerListView.setDropListener(new DragSortListView.DropListener() {
            @Override
            public void drop(int from, int to) {
                if (from != to) {
//                    DragSortListView list = getListView();
                    PlaydeatalData.DataBean.ListBean item = (PlaydeatalData.DataBean.ListBean) adapter.getItem(from);
                    adapter.remove(from);
                    adapter.insert(item, to);
//                    list.moveCheckState(from, to);
//                    Log.d("DSLV", "Selected item is " + list.getCheckedItemPosition());
                }
            }
        });
        footerListView.setDragListener(new DragSortListView.DragListener() {
            @Override
            public void drag(int from, int to) {
                if (from != to) {
//                    DragSortListView list = getListView();
//                    String item = adapter.getItem(from);
//                    adapter.remove(item);
//                    adapter.insert(item, to);
//                    list.moveCheckState(from, to);
//                    Log.d("DSLV", "Selected item is " + list.getCheckedItemPosition());
                }
            }
        });
        footerListView.setDragEnabled(false);
        rl_cover_delete.setOnClickListener(this);
        rl_cover_add.setOnClickListener(this);
    }

    private void delAudio(String coverId,String audio){
        DBFloatPlaylist data = DBFloatPlayListDaoHelp.queryBuilderById(getThis(),coverId);
        if(data!=null){
            ArrayList<String> listAudioIds = new ArrayList<>();
            String[] audios = data.getList_audio().split(",");
            for(String audioId : audios){
                if (!TextUtils.isEmpty(audioId)) {
                    listAudioIds.add(audioId);
                }
            }

            listAudioIds.remove(audio);
//            for(String delId : audioDelList){
//                listAudioIds = removeId(listAudioIds,delId);
//            }


            StringBuffer result = new StringBuffer();
            for(String resultId : listAudioIds){
                result.append(resultId);
                result.append(",");
            }

            String newAudios = "";
            if(result!=null&&result.length()>0){
                newAudios = result.substring(0,result.length()-1);
            }
            data.setList_audio(newAudios);
            data.setList_count(String.valueOf(Integer.parseInt(data.getList_count())-1));

            //FIXME 此方法会修改播单的_id
//            DBHelper.getInstance(getThis()).delPlayList(playlistID);
//            DBHelper.getInstance(getThis()).addList(data);
            DBFloatPlayListDaoHelp.update(getThis(),data);

            EventBus.getDefault().post(new NotifyMyPlaylist("notify"));
            refreshDataSize();
        }
    }

    //界面退出的时候统一删除，因为单一删除会修改播单的id
    private void delAudio4List(String playlistID,List<String> audioDelList){
//        FloatPlayListData data = DBHelper.getInstance(getThis()).queryListDataByID(playlistID);
        DBFloatPlaylist data = DBFloatPlayListDaoHelp.queryBuilderById(getThis(),playlistID);
        if(data!=null){
            ArrayList<String> listAudioIds = new ArrayList<>();
            String[] audios = data.getList_audio().split(",");
            for(String audioId : audios){
                if (!TextUtils.isEmpty(audioId)) {
                    listAudioIds.add(audioId);
                }
            }
            //能写这个代码的都是大神
            for(String delId : audioDelList){
//                listAudioIds = removeId(listAudioIds,delId);
                listAudioIds.remove(delId);
            }

            StringBuffer result = new StringBuffer();
            for(String resultId : listAudioIds){
                result.append(resultId);
                result.append(",");
            }

            String newAudios = "";
            if(result!=null&&result.length()>0){
                newAudios = result.substring(0,result.length()-1);
            }
            data.setList_audio(newAudios);
            data.setList_count(String.valueOf(Integer.parseInt(data.getList_count())-audioDelList.size()));

            //FIXME 此方法会修改播单的_id
//            DBHelper.getInstance(getThis()).delPlayList(playlistID);
//            DBHelper.getInstance(getThis()).addList(data);
            DBFloatPlayListDaoHelp.update(getThis(),data);
            ShareCollectCallBackUtils.collectCallBack(audioDelList,"-1","0");
//            EventBus.getDefault().post(new NotifyMyPlaylist("notify"));
        }
    }

    private ArrayList<String> removeId(ArrayList<String> list,String id){
        ArrayList<String> result = new ArrayList<>();
        for(String temp : list){
            if(temp.equals(id)){
                continue;
            }
            result.add(temp);
        }
        return result;
    }

//    private ArrayList<String> delAudioIds = new ArrayList<>();
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void XXX(NotifyPlayDetal messageEvent) {
        if (messageEvent.getMessage()=="share"){
            messageEvent.getListBean();
            try {

                new CopyShareFragment().show(getSupportFragmentManager(), "Dialog");
            }catch (Exception e){
                //解决 IllegalStateException: Can not perform this action after onSaveInstanceState
                e.printStackTrace();
            }
        }else if (messageEvent.getMessage()=="remove"){//这里需要加入删除数据库的操作
            for (int i=0;i<datas.size();i++){

                if (datas.get(i).getId().equals(messageEvent.getListBean().getId())){
//                    Toast.makeText(getThis(),datas.get(i).getId(),Toast.LENGTH_SHORT).show();
                    datas.remove(i);
                    adapter.notifyDataSetChanged();//TODO
//                    DBHelper.getInstance(getThis()).delAudios();
//                    adapter.setList(listBean);
//                    Toast.makeText(getThis(),"删除成功",Toast.LENGTH_SHORT).show();
                    delAudio(mPlaylistData.getId()+"",messageEvent.getListBean().getId());
//                    delAudioIds.add(messageEvent.getListBean().getId());
                    showToast("移除成功");
                    ShareCollectCallBackUtils.collectCallBack(messageEvent.getListBean().getId(),"-1","0");
                    break;
                }
            }

        }else {//
            RecommendFeed.DataBean.ListBean bean= new RecommendFeed.DataBean.ListBean();
            for (int i = 0; i < datas.size(); i++) {
                if (messageEvent.getListBean().getId().equals(datas.get(i).getId())){
                    PlaydeatalData.DataBean.ListBean mbean =datas.get(i);

                    bean.setDuration(mbean.getDuration());
                    bean.setCategory_id(mbean.getCover_id());
                    bean.setId(mbean.getId());
                    bean.setCollect(mbean.getCollect());
                    bean.setShare(mbean.getShare());
                    bean.setStar(mbean.getStar());
                    bean.setTitle(mbean.getTitle());
                    bean.setUrl(mbean.getUrl());
                    bean.setCover_pic(mbean.getPic());

                    Intent addIntent = new Intent(getThis(), Add2ListActivity.class);
                    Bundle bundle = new Bundle();
                    bundle.putSerializable(AUDIO_ID,bean);
                    addIntent.putExtras(bundle);
                    getThis().startActivity(addIntent);
                }
            }

        }
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()){
            case R.id.ll_share:
                if (datas.size()==0){
                    break;
                }
                isManager = true;
                footerListView.setDragEnabled(true);
//                new CustomBottomSheetDialogFragment(sharedata).show(getSupportFragmentManager(), "Dialog");//展示分享弹窗
//                Toast.makeText(PlayDetailMineActivity.this,"管理",Toast.LENGTH_LONG).show();
                ll_share.setVisibility(View.GONE);
                iv_back.setVisibility(View.GONE);
                tv_cancel.setVisibility(View.VISIBLE);
                tv_select_all.setVisibility(View.VISIBLE);
                ll_manager.setVisibility(View.VISIBLE);
                startManager();
                break;
            case R.id.ll_back://bar 返回键
                if (isManager){
                    isManager = false;
                    footerListView.setDragEnabled(false);
                    ll_share.setVisibility(View.VISIBLE);
                    iv_back.setVisibility(View.VISIBLE);
                    tv_cancel.setVisibility(View.GONE);
                    tv_select_all.setVisibility(View.GONE);
                    ll_manager.setVisibility(View.GONE);
                    //取消
                    cancelManager();
                    tv_select_all.setText("全选");
                    //排序更新
                    refreshSort();
                }else{
                    finish();
                }
//                if(ISBODAN){
//                    delAudio4List(mPlaylistData.getId()+"",delAudioIds);
//                }
//                finish();
                break;
            case R.id.tv_select_all:
                //全选
                if ("全选".equals(tv_select_all.getText())){
                    selectAll();
                    tv_select_all.setText("取消\n全选");
                }else{
                    cancelSelectAll();
                    tv_select_all.setText("全选");
                }
                break;
            case R.id.rl_cover_delete:
                deleteCover();
                break;
            case R.id.rl_cover_add:
                addCover();
                break;
        }
    }

    private void addCover() {
        if (adapter != null){
            ArrayList<String> select2 = adapter.getSelect2();
            if (select2.size()> 0){
//                delAudio4List(mPlaylistData.getId()+"",select2);
                Intent addIntent = new Intent(getThis(), Add2ListActivity.class);
                Bundle bundle = new Bundle();
                bundle.putSerializable("my_cover",select2);
                addIntent.putExtras(bundle);
                getThis().startActivity(addIntent);
            }else{
                showToast("请选择要收藏的音频");
            }
        }
    }

    private void refreshSort(){
        DBFloatPlaylist data = DBFloatPlayListDaoHelp.queryBuilderById(getThis(),mPlaylistData.getId()+"");
        if(data!=null){

            StringBuffer result = new StringBuffer();
            for(PlaydeatalData.DataBean.ListBean resultId : datas){
                result.append(resultId.getId());
                result.append(",");
            }

            String newAudios = "";
            if(result!=null&&result.length()>0){
                newAudios = result.substring(0,result.length()-1);
            }
//            newAudios = result.toString();
            data.setList_audio(newAudios);
            data.setList_count(String.valueOf(datas.size()));

            //FIXME 此方法会修改播单的_id
//            DBHelper.getInstance(getThis()).delPlayList(playlistID);
//            DBHelper.getInstance(getThis()).addList(data);
            DBFloatPlayListDaoHelp.update(getThis(),data);

            EventBus.getDefault().post(new NotifyMyPlaylist("notify"));
        }
    }

    private ProgressDialog progressDialog;
    private void showProgressDialog(){
        if (progressDialog == null){
            progressDialog = new ProgressDialog(this,android.R.style.Theme_Material_Light_Dialog_Alert);
            progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
            progressDialog.setCancelable(false);
            progressDialog.setCanceledOnTouchOutside(false);
            progressDialog.setMessage("加载数据中");
        }

        progressDialog.show();
    }

    private void hideProgressDialog(){
        if (progressDialog != null){
            if (progressDialog.isShowing()){
                progressDialog.dismiss();
            }
        }
    }

    private void deleteCover(){
        if (adapter != null){
            final ArrayList<String> select2 = adapter.getSelect2();
            if (select2.size()> 0){
                showProgressDialog();
                Observable.create(new ObservableOnSubscribe<Object>() {
                    @Override
                    public void subscribe(ObservableEmitter<Object> emitter) throws Exception {
                        delAudio4List(mPlaylistData.getId()+"",select2);
                        emitter.onNext("");
                        emitter.onComplete();
                    }
                }).subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread())
                        .subscribe(new Observer<Object>() {
                            @Override
                            public void onSubscribe(Disposable d) {

                            }

                            @Override
                            public void onNext(Object o) {
                                hideProgressDialog();
                                EventBus.getDefault().post(new NotifyMyPlaylist("notify"));
                                adapter.deleteList(select2);
                            }

                            @Override
                            public void onError(Throwable e) {

                            }

                            @Override
                            public void onComplete() {

                            }
                        });

            }else{
                showToast("请选择要删除的音频");
            }
        }
    }

    private void selectItem(int position){
        if (adapter != null){
            adapter.selectItem(position);
        }
    }

    private void cancelSelectAll(){
        if (adapter != null){
            adapter.cancelSelectAll();
        }
    }

    private void cancelManager(){
        if (adapter != null){
            adapter.cancelManager();
        }

    }

    private void startManager(){
        if (adapter != null){
            adapter.startManager();
        }
    }

    private void selectAll(){
        if (adapter != null){
            adapter.selectAll();
        }
    }

    private void showBottomSheet(BottomSheetBehavior behavior) {
        if (behavior.getState() == BottomSheetBehavior.STATE_HIDDEN) {
            behavior.setState(BottomSheetBehavior.STATE_COLLAPSED);
        } else {
            behavior.setState(BottomSheetBehavior.STATE_HIDDEN);
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
        if (mHandler != null){
            mHandler.removeCallbacksAndMessages(null);
            mHandler = null;
        }
    }

    @Override
    public void onBackPressed() {
        if (isManager){

        }else {
            super.onBackPressed();
        }
    }




    //以下代码解决 IllegalStateException: Can not perform this action after onSaveInstanceState

    private Method noteStateNotSavedMethod;
    private Object fragmentMgr;
    private String[] activityClassName = {"Activity", "FragmentActivity"};

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        invokeFragmentManagerNoteStateNotSaved();
    }

    private void invokeFragmentManagerNoteStateNotSaved() {
        //java.lang.IllegalStateException: Can not perform this action after onSaveInstanceState
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.HONEYCOMB) {
            return;
        }
        try {
            if (noteStateNotSavedMethod != null && fragmentMgr != null) {
                noteStateNotSavedMethod.invoke(fragmentMgr);
                return;
            }
            Class cls = getClass();
            do {
                cls = cls.getSuperclass();
            } while (!(activityClassName[0].equals(cls.getSimpleName())
                    || activityClassName[1].equals(cls.getSimpleName())));

            Field fragmentMgrField = prepareField(cls, "mFragments");
            if (fragmentMgrField != null) {
                fragmentMgr = fragmentMgrField.get(this);
                noteStateNotSavedMethod = getDeclaredMethod(fragmentMgr, "noteStateNotSaved");
                if (noteStateNotSavedMethod != null) {
                    noteStateNotSavedMethod.invoke(fragmentMgr);
                }
            }

        } catch (Exception ex) {
        }
    }

    private Field prepareField(Class<?> c, String fieldName) throws NoSuchFieldException {
        while (c != null) {
            try {
                Field f = c.getDeclaredField(fieldName);
                f.setAccessible(true);
                return f;
            } finally {
                c = c.getSuperclass();
            }
        }
        throw new NoSuchFieldException();
    }

    private Method getDeclaredMethod(Object object, String methodName, Class<?>... parameterTypes) {
        Method method = null;
        for (Class<?> clazz = object.getClass(); clazz != Object.class; clazz = clazz.getSuperclass()) {
            try {
                method = clazz.getDeclaredMethod(methodName, parameterTypes);
                return method;
            } catch (Exception e) {
            }
        }
        return null;
    }
}
